import { reqUserCode, reqUserRegister, reqUserLogin, reqCheckingToken, reqLogout } from '@/api'

// 暴露小仓库
export default {         
  actions: {
    // 获取验证码
    async getusercode({ commit }, phone) {
      let res = await reqUserCode(phone)
      if (res.code === 200) {
        commit('GETUSERCODE', res.data)
        return 'ok'
      } else {
        return Promise.reject(new Error(resllt.message))
      }
    },
    // 注册的回调
    async userRegister({ commit, dispatch, state, getters }, data) {
      let result = await reqUserRegister(data)
      if (result.code === 200) {
        return 'ok'
      } else {
        return Promise.reject(new Error(result.message))
      }
    },
    // 登录的回调
    async UserLogin({ commit, state, dispatch, getters }, data) {
      let result = await reqUserLogin(data)
      console.log(result);
      if (result.code === 200) {
        commit('UPDATETOKEN',result.data.token)
        return result.data
      } else {
        return Promise.reject(new Error(result.message))
      }
    },
    // 验证token
    async checkingToken({ commit }) {
      let result = await reqCheckingToken()
      if (result.code === 200) {
        commit('UPDATENICKNAME',result.data.nickName)
        commit('UPDATEISLOGIN',true)  
        return result.data.nickName
      } else {
        return Promise.reject(new Error(result.message))
      }
    },
    // 退出登录
    async Userlogout({ commit }) {
      let res = await reqLogout()
      if (res.code === 200) {
        // console.log(res);
        commit('UPDATEISLOGIN', false)
        commit('UPDATENICKNAME',null)
        commit('UPDATETOKEN','') 
        localStorage.removeItem('token')
        return 'ok'
      }else{
        return Promise.reject(new Error(res.message))
      }
    },
  },
  mutations: {
    GETUSERCODE(state, value) {
      state.code = value
    },
    // 修改是否登录
    UPDATEISLOGIN(state, value) {
      state.isLogin = value
    },
    UPDATENICKNAME(state, value) {
      state.nickName = value
    },
    // 
    UPDATETOKEN(state,value){
        state.token = value
    }
  },
  state: {
    code: '',        //存放验证码的初始值
    isLogin: false,  //是否登录,默认没登录
    nickName: null,   //保存用户名
    token:localStorage.getItem('token'),
  },
}